package models

import (
	"log"
	"rongyy/src/app"
)

type CompetitionModel struct {
	BaseModel   `xorm:"extends"`
	OrderSn     string  `json:"order_sn"`
	Price       float64 `json:"price"`
	Amount      int     `json:"amount"`
	Status      string  `json:"status"`
	MerchantId  int64   `json:"merchant_id"`
	Remark      string  `json:"remark"`
	CompanyInfo string  `json:"company_info"`
	Content     string  `json:"content"`
}

type ReqCompetitionQuery struct {
	Limit   int    `json:"limit"`
	Offset  int    `json:"offset"`
	OrderSn string `json:"order_sn"`
	Status  string `json:"status"`
}

func (rm *CompetitionModel) TableName() string {
	return "competition"
}

func (rm *CompetitionModel) Create() error {
	_, err := app.DB().Insert(rm)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

//	func (rm *OrdersModel) UpdateOrderStatus() error {
//		if rm.OrderSn == "" {
//			return errors.New("订单号缺失")
//		}
//		_, err := app.DB().Where("order_sn=? ", rm.OrderSn).Cols("pay_status").Update(rm)
//		if err != nil {
//			return err
//		}
//		return err
//	}
//
//	func (rm *OrdersModel) FindByStatus(orderSn string, status int) (bool, error) {
//		po := &OrdersModel{}
//		has, err := app.DB().Where("order_sn=? and order_status=?", orderSn, status).Get(po)
//		if err != nil {
//			log.Println(err)
//			return false, err
//		}
//		return has, nil
//	}
func (rm *CompetitionModel) FindByOrder(req *ReqCompetitionQuery) ([]CompetitionModel, int64, error) {
	pos := make([]CompetitionModel, 0)
	s := app.DB().Table("competition")
	if req.OrderSn != "" {
		s = s.Where("order_sn=?", req.OrderSn)
	}
	if req.Status != "" {
		s = s.Where("status=?", req.Status)
	}
	total, err := s.Limit(req.Limit, req.Offset).FindAndCount(&pos)
	if err != nil {
		return nil, 0, err
	}
	return pos, total, nil
}

func (rm *CompetitionModel) FindByOrderAndMerchant(orderSn string, mid int64) (*CompetitionModel, bool, error) {
	po := &CompetitionModel{}
	has, err := app.DB().Where("order_sn=? and merchant_id=?", orderSn, mid).Get(po)
	if err != nil {
		return nil, false, err
	}
	return po, has, nil
}

func (rm *CompetitionModel) Accept(req *CompetitionModel) error {
	req.Status = "accept"
	_, err := app.DB().Where("order_sn=? and merchant_id=?", req.OrderSn, req.MerchantId).Cols("status").Update(req)
	return err
}
